package com.fzl.spring_chatroom.common.interceptor;

import com.fzl.spring_chatroom.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    //约定前端用户的token放在handler
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String user_token = request.getHeader("user_token");
        log.info("从handler中获取token:"+user_token);
        if(user_token == null) {
            //拦截
            response.setStatus(401);
            return false;
        }
        //校验token是否合法
        Claims token = JwtUtils.parseToken(user_token);
        if(token == null) {
            response.setStatus(401);
            return false;
        }

        return true;
        //return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}